package com.monitoringfloty.androidclient;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

/**
 * This shows how to create a simple activity with a map and a marker on the map.
 * <p>
 * Notice how we deal with the possibility that the Google Play services APK is not
 * installed/enabled/updated on a user's device.
 */

public class MainActivity extends FragmentActivity 
		implements OnMapClickListener, OnMapLongClickListener, OnCameraChangeListener, SettingsListener {
    private static final int MAP_TYPE_NORMAL = 1;
	private static final int MAP_TYPE_SATELLITE = 2;
	private static final int MAP_TYPE_TERRAIN = 3;
	private static final int MAP_TYPE_HYBRID = 4;
	/**
     * Note that this may be null if the Google Play services APK is not available.
     */
    private GoogleMap mMap;
    private MarkerOptions myPos;
    private Marker mark;
    private SettingsSingleton settings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        settings = SettingsSingleton.getInstance();
        settings.setContext(getApplicationContext());
        
        setUpMapIfNeeded();
        settings.addListener(this);
        positionUpdater.getInstance().setContext(getApplicationContext());
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not have been
     * completely destroyed during this process (it is likely that it would only be stopped or
     * paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
     * {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();

            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.setOnMapClickListener(this);
        mMap.setOnMapLongClickListener(this);
        mMap.setOnCameraChangeListener(this);
        mMap.setMyLocationEnabled(settings.getBool("ShowMyPosOnMap", false));
        //mMap.setMyLocationEnabled();
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(51.75,19.42),(float)5.0));
    }
    
    @Override
    public void onMapClick(LatLng point) {
        //mTapTextView.setText("tapped, point=" + point);
    	Toast.makeText(getApplicationContext(), "Pressed:"+point, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onMapLongClick(LatLng point) {
        //mTapTextView.setText("long pressed, point=" + point);
    	if(mark!=null)
    		mark.remove();
    	if(myPos==null) {
    		myPos = new MarkerOptions();
    	}
		myPos.position(point).title("WYBRANE");

		String s = positionUpdater.getInstance().SendPos(point.latitude, point.longitude);
		if(s!="Success")
			Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
		else {
			mark=mMap.addMarker(myPos);
		}
    }

    @Override
    public void onCameraChange(final CameraPosition position) {
        //mCameraTextView.setText(position.toString());
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
   }
    
    @Override
    public void onBackPressed() {
        // do something on back.
    	positionUpdater.getInstance().close();
    	super.onBackPressed();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
    	Intent myIntent;
        switch (item.getItemId()) {
	        case R.id.mode_action:
	        	switch(mMap.getMapType()) {
	        		case MAP_TYPE_NORMAL:
	        			mMap.setMapType(MAP_TYPE_SATELLITE);
	        			Toast.makeText(getApplicationContext(), "Changed to Satellite", Toast.LENGTH_SHORT).show();
	        			break;
	        		case MAP_TYPE_SATELLITE:
	        			mMap.setMapType(MAP_TYPE_TERRAIN);
	        			Toast.makeText(getApplicationContext(), "Changed to Terrain", Toast.LENGTH_SHORT).show();
	        			break;
	        		case MAP_TYPE_TERRAIN:
	        			mMap.setMapType(MAP_TYPE_HYBRID);
	        			Toast.makeText(getApplicationContext(), "Changed to Hybrid", Toast.LENGTH_SHORT).show();
	        			break;
	        		case MAP_TYPE_HYBRID:
	        			mMap.setMapType(MAP_TYPE_NORMAL);
	        			Toast.makeText(getApplicationContext(), "Changed to Normal", Toast.LENGTH_SHORT).show();
	        			break;
	        	}
	        	return true;
	        	
	        case R.id.gps_action:
	            myIntent=new Intent(getBaseContext(),GpsActivity.class);
	            startActivityForResult(myIntent,1);
	            return true;
	            
            case R.id.action_settings:
                myIntent=new Intent(getBaseContext(),SettingsActivity.class);
                startActivityForResult(myIntent,1);
                //finish();
                return true;
                
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	setUpMap();
    }
    
	@Override
	public void onSettingsUpdate(int[] wyniki) {
		// TODO Auto-generated method stub
		setUpMap();
		
	}
}
